import db from '../utils/dbconf'
import { encode, decode } from 'js-base64'
import { SQL_ERROR } from '../server.config.js'
const TABLE_NAME = 'USERS'

export default{
  doLog:async ({body}, res, next) => {
    try{
    	const { account,password } = body
    	const uinfo = 
    	  await db.table(TABLE_NAME)
    	  .where({account})
    	  .find()
    	const { id,password:surepass,type,delete:isdelete,ava } = uinfo
    	delete(uinfo.account)
    	delete(uinfo.password)
    	if(isdelete || !id) return res.send({code:500,msg:'账户不存在'})
    	if(surepass !== password) return res.send({code:500,msg:'用户名或密码错误'})
    	const token = encode(JSON.stringify({id,account,password,type}))
      // uinfo.ava = `//${QINIU.ava_domain_name}/${ava}`
    	return res.send({
    	  code: 200,
    	  data:{uinfo,token}
    	})
    }catch(e){
    	res.send(SQL_ERROR)
    }
  },
  tokenlogin:async ({body:{token}},res,next) => {
    try{
      const { id,account,password,type } = JSON.parse(decode(token))
      const uinfo =
        await db.table(TABLE_NAME)
        .where({id})
        .find()
      const { account:acc,password:pass,type:tp,ava } = uinfo
      delete(uinfo.account)
      delete(uinfo.password)
      if( acc!==account || pass!==password || tp!== type)
        return res.send({code:500,msg:'账户已过期'})
      // uinfo.ava = `//${QINIU.ava_domain_name}/${ava}`
      return res.send({
        code:200,
        data:{uinfo}
      })
    }catch(e){
      console.log({e})
      return res.send({code:500,msg:'请重新登录'})
    }
  },
  doReg:async ({body}, res, next) => {
    try{
      const { id,type } = res.locals
      if(type !== 99) return res.send({code:500,msg:'用户权限异常'})
      const { user,user:{account,name}} = body
      if(!name) user.name='新用户'
      const only = await db.table(TABLE_NAME)
        .thenAdd(user,{account},true)
        .then(({id,type})=>type==='exist')
      return res.send(
        only?
          {code:500,msg:'该用户已存在（可能是账号重复）'}:
          {code:200}
      )
    }catch(e){
      return res.send(SQL_ERROR)
    }
  },
  doWriteOff:async ({body}, res, next) => {
    try{
      const { id,type } = res.locals
      if(type !== 99) return res.send({code:500,msg:'用户权限异常'})
      const { uid } = body
      const num = await db.table(TABLE_NAME)
        .where({id:uid})
        .delete()
        .then(num=>num)
      return res.send(
        num===1?
          {code:200}:
          {code:500,msg:'出现了根本不可能出现的问题...'},
      )
    }catch(e){
      return res.send(SQL_ERROR)
    }
  },
  
  updatename:async ({body:{name}},res,next) =>{
    const { id } = res.locals
    await db.table(TABLE_NAME).where({id}).update({name})
    return res.send({code:200})
  },
  updatePassword:async ({body},res,next) => {
    const { origin,new:password,sure } = body
    const { id } = res.locals
    if(origin === password || password !== sure) return res.send({code:500,msg:'哦不要这样...'})
    const num = await db.table(TABLE_NAME).where({id,password:origin}).update({password}).then(num=>num)
    return res.send(num===1?{code:200}:{code:500,msg:'原密码输入错误'})
  },
  
  updateAvatar:async ({body},res,next) => {
    try{
      const { oldname,newname } = body    
      const { id } = res.locals
      /**
       * 调用 七牛  -  删除旧文件
       */
      console.log({body,id})
      await db.table(TABLE_NAME).where({id}).update({ava:newname})
      return res.send({code:200})
    }catch(e){
      return res.send(SQL_ERROR)
    }
  },
  
  selectAllUser:async ({query:{ page,pageconf } },res,next) => {
    try{
      const { pagesize,getpass,like,type } = JSON.parse(pageconf)
      if(!type || !type.length)
        return res.send({code:200,data:{users:[],total:0}})
      const { type:u_type } = res.locals
      if(u_type != 99) return res.send({code:500,msg:'用户权限异常'})
      let total
      const where_like = like? `
        account like '%${like}%' or realname like '%${like}%'
      `:' true '
      if(page == 1)
        total = await db.table(TABLE_NAME)
          .where(where_like)
          .where({type:['IN',[...type]]})
          .count('id')
      const users = await db.table(TABLE_NAME)
        .where(where_like)
        .where({type:['IN',[...type]]})
        .field(getpass?'':'password',true)
        .page(page,pagesize).select()
      return res.send({code:200,data:{users,total}})
    }catch(e){
      return res.send(SQL_ERROR)
    }
  }
}